package com.icim.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class ICIMContextLoaderListener extends
		org.springframework.web.context.ContextLoaderListener {

	private static Logger logger = Logger
			.getLogger(ICIMContextLoaderListener.class);

	/**
	 * Initialize the root web application context.
	 *
	 * @param event
	 *            ServletContextEvent
	 */
	public void contextInitialized(ServletContextEvent event) {
		Context initCtx;
		try {
			initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");

//			initLog4jProc(envCtx);

			initLoadHistoryProc(envCtx);

			envCtx.close();
			initCtx.close();
		} catch (NamingException ex) {
			logger.error(ex.toString());
			System.setProperty("initPath", "");
		} catch(FileNotFoundException ex){
			logger.error(ex.toString());
			System.setProperty("initPath", "");
		}catch (Exception ex) {
			logger.error(ex.toString());
			System.setProperty("initPath", "");
		}
		logger.info("========================Loadhis start success=============");
		super.contextInitialized(event);
	}

	private String initLoadHistoryProc(Context envCtx) throws NamingException,
			FileNotFoundException {
		String config = null;

		config = (String) envCtx.lookup("initLoadHistoryFile");

		if (config == null) {
			throw new FileNotFoundException(
					"can not found configure file [initLoadHistoryFile] in context.xml");
		}
		System.setProperty("initFile", config);

		logger.info("========================config file path============="
				+ config);
		return config;
	}

	private String initLog4jProc(Context envCtx) throws NamingException,
			FileNotFoundException {
		String config;
		InputStream is = null;

		config = (String) envCtx.lookup("loadHistoryLog4j");
		if (config == null) {
			throw new FileNotFoundException(
					"can not found configure file [loadHistoryLog4j] in context.xml");
		}
		is = new FileInputStream(new File(config));

		PropertyConfigurator.configure(is);

		logger.info("========================config file path============="
				+ config);
		return config;
	}
}
